using System;
using System.ComponentModel;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using CSW.Framework.Common;
using CSW.Framework.Linq;
using CSW.Framework.UI.DevEx.UserControls;

namespace CSW.Framework.UI.DevEx
{
    /// <summary>
    /// In-place Edit Grid Controller.  Type safe access to <see cref="DXGridControl" />.
    /// </summary>
    /// <typeparam name="T">The business object item.</typeparam>
    public class InplaceEditGridController<T> : TypedGridControllerLinq<T>
        where T : class, IBusinessObjectLinq
    {
        /// <summary>
        /// Occurs when an item is added to the data source.
        /// </summary>
        public event EventHandler<DataEventArgs<T>> ItemAdded;

        private BindingList<T> m_PreviousDataSource;

        /*/// <summary>
        /// Initializes a new instance of the <see cref="InplaceEditGridController{T}"/> class.
        /// </summary>
        /// <param name="gridControl">The grid control.</param>
        public InplaceEditGridController(BaseGridControl gridControl)
            : this(gridControl, null, true)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="InplaceEditGridController{T}"/> class.
        /// </summary>
        /// <param name="gridControl">The grid control.</param>
        /// <param name="multiSelect">if set to <c>true</c>, multi select is enabled (default = true).</param>
        public InplaceEditGridController(BaseGridControl gridControl, bool multiSelect)
            : this(gridControl, null, multiSelect)
        {
        }*/

        /// <summary>
        /// Initializes a new instance of the <see cref="InplaceEditGridController{T}"/> class.
        /// </summary>
        /// <param name="gridControl">The grid control.</param>
        /// <param name="exportFileName">Name of the export file, minus the extension.</param>
        public InplaceEditGridController(DXGridControl gridControl, string exportFileName)
            : this(gridControl, exportFileName, true)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="InplaceEditGridController{T}"/> class.
        /// </summary>
        /// <param name="gridControl">The grid control.</param>
        /// <param name="exportFileName">Name of the export file, minus the extension.</param>
        /// <param name="multiSelect">if set to <c>true</c>, multi select is enabled (default = true).</param>
        public InplaceEditGridController(DXGridControl gridControl, string exportFileName, bool multiSelect)
            : base(gridControl, exportFileName, multiSelect)
        {
            GridView.OptionsBehavior.Editable = true;
            GridView.OptionsSelection.EnableAppearanceFocusedCell = true;
            GridView.FocusRectStyle = DrawFocusRectStyle.CellFocus;
            GridView.OptionsSelection.MultiSelect = multiSelect;
            Grid.TabStop = true;

            GridView.DataSourceChanged += m_GridView_DataSourceChanged;
            HookDataSource();

            AddRecordCount();
        }

        /// <summary>
        /// Makes the grid editable.  Uses the embedded navigator.
        /// </summary>
        /// <param name="addRecordCount">if set to <c>true</c>, adds a record count to the bottom of the grid.</param>
        /// <param name="allowAppend">if set to <c>true</c>, adds an append button.</param>
        /// <param name="allowRemove">if set to <c>true</c>, adds a remove button.</param>
        /// <param name="handleRemove">if set to <c>true</c>, handles the remove button click.</param>
        public void Setup(bool addRecordCount, bool allowAppend, bool allowRemove, bool handleRemove)
        {
            if (!addRecordCount)
                Grid.EmbeddedNavigator.TextLocation = NavigatorButtonsTextLocation.None;
            else
                Grid.EmbeddedNavigator.TextStringFormat = "Record {0:#,0} of {1:#,0}";

            if (allowAppend)
            {
                Grid.EmbeddedNavigator.Buttons.Append.Visible = true;
            }

            if (allowRemove)
            {
                Grid.EmbeddedNavigator.Buttons.Remove.Visible = true;
                GridView.OptionsView.ShowIndicator = true;
                if (handleRemove)
                    Grid.EmbeddedNavigator.ButtonClick += EmbeddedNavigator_RemoveButtonClick;
            }
        }

        private void m_GridView_DataSourceChanged(object sender, EventArgs e)
        {
            HookDataSource();
        }

        private void HookDataSource()
        {
            if (m_PreviousDataSource != null)
                m_PreviousDataSource.ListChanged -= DataSource_ListChanged;

            if (DataSource != null)
                DataSource.ListChanged += DataSource_ListChanged;

            m_PreviousDataSource = DataSource;
        }

        private void DataSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            if (e.ListChangedType == ListChangedType.ItemAdded)
            {
                T businessObject = DataSource[e.NewIndex];
                if (businessObject != null)
                {
                    //if (!businessObject.IsEditting)
                    //    businessObject.BeginEdit();

                    EventHandler<DataEventArgs<T>> itemAdded = ItemAdded;
                    if (itemAdded != null)
                        itemAdded(this, new DataEventArgs<T>(businessObject));
                }
            }
        }

        private void EmbeddedNavigator_RemoveButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (e.Button.ButtonType == NavigatorButtonType.Remove)
            {
                DialogResult result = MessageBox.Show("Remove selected record(s)?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                GridView.CloseEditor();
                if (result != DialogResult.Yes)
                {
                    e.Handled = true;
                }
                else
                {
                    GridView.CloseEditor();
                    GridView.UpdateCurrentRow();
                }
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public override void Dispose()
        {
            GridView.DataSourceChanged -= m_GridView_DataSourceChanged;
            Grid.EmbeddedNavigator.ButtonClick -= EmbeddedNavigator_RemoveButtonClick;
            
            if (DataSource != null)
                DataSource.ListChanged -= DataSource_ListChanged;

            base.Dispose();
        }
    }
}
